﻿using Android.App;
using Android.OS;
using Android.Widget;
using Android.Net.Wifi;
using Android.Support.V4.Widget;
using static Android.Net.Wifi.WifiManager;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Text;
using System.Net.Sockets;
using System;
using Android.Util;
using Android.Content;
using Android.Graphics;

namespace LePcCtrlApp
{
    [Activity(Label = "@string/app_name", Theme = "@android:style/Theme.Light.NoTitleBar", MainLauncher = true)]
    public class MainActivity : Activity,IDialogInterfaceOnClickListener
    {
        private SwipeRefreshLayout refreshLayout;
        private ListView listitem;
        WifiManager manager;
        MulticastLock wifilock;
        List<string> items;
        ArrayAdapter<string> liststring;
        protected override void OnCreate(Bundle bundle)
        {
            RequestedOrientation =Android.Content.PM.ScreenOrientation.Landscape;
            base.OnCreate(bundle);

            manager = (WifiManager)GetSystemService(Context.WifiService);
            wifilock = manager.CreateMulticastLock("le_dian_wifi");
            SetContentView(Resource.Layout.MainActivity);

            listitem = FindViewById<ListView>(Resource.Id.listView1);
            items = new List<string>();
            liststring = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleExpandableListItem1, items);
            listitem.Adapter = liststring;
            refreshLayout = FindViewById<SwipeRefreshLayout>(Resource.Id.swipeRefreshLayout);
            refreshLayout.SetColorSchemeColors(Color.Red, Color.Green, Color.Blue, Color.Yellow);
            refreshLayout.Refresh += RefreshLayout_Refresh;
            listitem.ItemClick += Listitem_ItemClick;
            RefreshLayout_Refresh(null, null);
        }

        private async void Listitem_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            string text = liststring.GetItem(e.Position);
            if (text != null)
            {
                string[] tag = text.Split(':');
                if (tag.Length != 2)
                    return;
                Task<bool> ConnectSync = LoginManager.GetInstance().Connect(tag[0], tag[1]);
                bool Connect = await ConnectSync;
                if (Connect)
                {
                    Task<int> ReceiveSync = LoginManager.GetInstance().Receive();
                    int x = await ReceiveSync;
                    if (x > 0)
                    {
                        string buf = Encoding.ASCII.GetString(LoginManager.GetInstance().Buffer);
                        int LinePos = buf.IndexOf("\n");
                        switch (buf.Substring(0, LinePos))
                        {
                            case "200":
                                StartActivity(typeof(CtrlActivity));
                                break;
                            case "401":
                                StartActivity(typeof(LoginActivity));
                                break;
                        }
                    }
                }
            }
        }

        private async void RefreshLayout_Refresh(object sender, EventArgs e)
        {
            wifilock.Acquire();
            items.Clear();
            UdpClient client = new UdpClient(1745);
            try
            {
                System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();               
               sw.Start();
                while (sw.ElapsedMilliseconds < 3000)
                {
                    
                    Task<UdpReceiveResult> receiveAsync = client.ReceiveAsync();
                    UdpReceiveResult ret = await TimeoutHelper.Timeout(receiveAsync, 3000);
                    string service = Encoding.ASCII.GetString(ret.Buffer);
                    string ip = ret.RemoteEndPoint.Address.ToString();
                    string[] buf = service.Split(':');
                    if (buf.Length != 2)
                        throw new ArgumentException("Arg error!");
                    string tag = ip + ":" + buf[1];
                    if (service != null && !items.Exists(delegate (string str) { return tag == str; }))
                    {
                        if (buf[0] == "LeDianRemoteControl")
                            items.Add(tag);
                    }
                }
                sw.Stop();
            }
            catch (Exception error)
            {
                Log.Error("ledianCtrl", error.ToString());
            }
            finally
            {
                if (items.Count == 0)
                    items.Add("下拉扫描计算机");
                liststring = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleExpandableListItem1, items);
                listitem.Adapter = liststring;
                liststring.NotifyDataSetChanged();
                refreshLayout.Refreshing = false;
                client.Close();
                wifilock.Release();
            }
        }
        
        public override void OnBackPressed()
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            //    设置Title的图标
            builder.SetIcon(Resource.Mipmap.ic_launcher);
            //    设置Title的内容
            builder.SetTitle("提示");
            //    设置Content来显示一个信息
            builder.SetMessage("确定退出吗？");
            //    设置一个PositiveButton
            builder.SetPositiveButton("确定", this);
            builder.SetNegativeButton("取消", this);
            builder.Show();
        }

        protected override void OnDestroy()
        {
            LoginManager.GetInstance().Close();
            base.OnDestroy();
        }

        public void OnClick(IDialogInterface dialog, int which)
        {
            if (which == (int)DialogButtonType.Positive)
            {
                BuildVersionCodes sdk_Version = Build.VERSION.SdkInt;
                if (sdk_Version >= BuildVersionCodes.Froyo)
                {
                    Intent startMain = new Intent(Intent.ActionMain);
                    startMain.AddCategory(Intent.CategoryVrHome);
                    startMain.SetFlags(ActivityFlags.NewTask);
                    StartActivity(startMain);
                    Process.KillProcess(Process.MyPid());
                }
                else if (sdk_Version < BuildVersionCodes.Froyo)
                {
                    ActivityManager activityMgr = (ActivityManager)GetSystemService(ActivityService);
                    activityMgr.RestartPackage(PackageName);
                }
            }
        }

    }
}